package ReentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:  锁超时的情况-->tryLock(long naio) 带参数的情况下
 * User: sfx
 * Date: 2022-12-27
 * Time: 16:12
 */

public class TestDemo4 {
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread() +"尝试获取锁");
            //为了防止无限制的等可以使用tryLock
            //当不带参数的时候,没有获取到锁之后就立即退出
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    //返回false,则代表没有获取到锁,直接退出
                    System.out.println(Thread.currentThread() +"没有获取到锁,直接退出");
                    return;
                }
            } catch (InterruptedException e) {
                //此时也有可能被其他线程打断
                e.printStackTrace();
                System.out.println( Thread.currentThread()+"线程被打断,返回");
                return;
            }
            //否则就是获取到锁
            try{
                System.out.println(Thread.currentThread() +"获取到锁");
            }finally {
                lock.unlock();
            }
        });
        lock.lock();
        t1.start();
        try {
            Thread.sleep(900);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + "释放锁");
        lock.unlock();
    }
}